<?php

namespace frontend\controllers;

use Yii;
use yii\data\ActiveDataProvider;
use frontend\models\News;
use frontend\models\NewsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * NewsController implements the CRUD actions for News model.
 */
class NewsController extends Controller
{

    /**
     * Lists all News models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new NewsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $this->layout = 'common';

        return $this->render('index', [
            'searchModel' => $searchModel,
            'newsDataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single News model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $newsModel = $this->findModel($id);

        $newsDataProvider = new ActiveDataProvider([
            'query' => News::find()->where(['>', 'date_public', $newsModel->date_public])->andWhere(['!=', 'id', $newsModel->id])->orderBy(['date_public' => SORT_ASC])->limit(3),
            'pagination' => false,
        ]);

        if($newsDataProvider->getTotalCount() < 3) 
        {
            $newsDataProvider = new ActiveDataProvider([
                'query' => News::find()->where(['!=', 'id', $newsModel->id])->orderBy(['date_public' => SORT_DESC])->limit(3),
                'pagination' => false,
            ]);
        }

        $this->layout = 'common';
        
        return $this->render('view', [
            'newsDataProvider' => $newsDataProvider,
            'model' => $newsModel,
        ]);
    }



    /**
     * Finds the News model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return News the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = News::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
